package com.sync.syncmasterdata.dingtask.service;


import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 钉钉 代办任务的Util 使用中台的钉钉app
 */
@Service
@Slf4j
public class DingTaskUtil {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RequestConfig config;

    @Autowired
    private CloseableHttpClient httpClient;

    @Value("${cloudpivotprops.url}")
    private String CPURL;

   /* private static final String CPAPPKEY = "dingasz4tirhmbrhqbkk";
    private static final String CPAPPSECRET = "8pQZxZ3578SnXeMgFmmpdew89g9RBDC8F7-9wTwdlKBLV9q4k5c5cB3v2YPz0z3t";*/

    public String getCPToken(String tag) throws Exception {
        String url = String.format("%s/api/systemInteg/getTokenByAppTag?appTag=%s", CPURL, tag);
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
        httpGet.setConfig(config);
        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            JSONObject jsonObject = new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            log.info("获取token", jsonObject.toString());
            if (jsonObject.getInt("code") == 1) {
                return jsonObject.getString("msg");

            } else {
                return null;
            }
        }

        return null;

    }

/**
     * 调用 钉钉 中台应用 获取token
     *
     * @return
     * @throws Exception
     *//*

    public String getTaskToken() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                // 中台的appkey
                .setAppKey(CPAPPKEY)
                // 中台的appSecret
                .setAppSecret(CPAPPSECRET);
        GetAccessTokenResponse rsp = client.getAccessToken(getAccessTokenRequest);
        System.out.println(objectMapper.writeValueAsString(rsp.getBody()));
        String access_token = rsp.getBody().getAccessToken();
        return access_token;
    }
*/

}
